package com.bookstore.controller;

import com.bookstore.domain.*;
import com.bookstore.domain.Error;
import com.bookstore.service.AddressService;
import com.bookstore.service.BookService;
import com.bookstore.service.OrderService;
import com.bookstore.service.ShoppingCartService;
import com.bookstore.utils.JsonUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private BookService bookService;
    @RequestMapping("/getOrders.do")
    @ResponseBody
    public String getOrders(Integer start, Integer pageSize, HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("loginUser");
        Error error = new Error();
        //处理数据
        if (start == null) {
            start = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        //从第一页开始，一页十行
        PageHelper.startPage(start, pageSize);
        String isPay_str = req.getParameter("isPay");
        String isDeliver_str = req.getParameter("isDeliver");
        String username = req.getParameter("username");
        Integer isPay = -1;
        Integer isDeliver = -1;
        if (isPay_str != null) {
            isPay = Integer.parseInt(isPay_str);
        }
        if (isDeliver_str != null) {
            isDeliver = Integer.parseInt(isDeliver_str);
        }
        if (username == null || username.equals("")) {
            username = null;
        }
        if (user == null) {
            error.setErrorInfo("请先登录。。。");
            error.setErrorType(1);
        } else {
            //验证用户身份
            System.err.println(user.getUid());
            if (user.getuType() == 0) { //0普通用户  无权限   1 商家只能查看自己的  2管理员  直接查看所有订单
                error.setErrorType(4);
                error.setErrorInfo("抱歉，权限不足！");
            } else if (user.getuType() == 1) {
                //只查询属于该商家的订单
                List<Order> orders = orderService.findAll(isPay, isDeliver, username, user.getUid());
                PageInfo<Order> pages = new PageInfo<Order>(orders);
                //验证ok 查询返回集合
                return JsonUtils.writeValueAsString(pages);
            } else if (user.getuType() == 2) {
                //查询所有订单
                List<Order> orders = orderService.findAll(isPay, isDeliver, username, 0);
                PageInfo<Order> pages = new PageInfo<Order>(orders);
                //验证ok 查询返回集合
                return JsonUtils.writeValueAsString(pages);
            }

        }
        //权限认证失败  返回错误信息
        return JsonUtils.writeValueAsString(error);
    }

    @RequestMapping("/getMyOrders.do")
    @ResponseBody
    public String getMyOrders(Integer start, Integer pageSize, HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("loginUser");
        Error error = new Error();
        //处理数据
        if (start == null) {
            start = 1;
        }
        if (pageSize == null) {
            pageSize = 5;
        }
        //从第一页开始，一页十行
        PageHelper.startPage(start, pageSize);
        String isPay_str = req.getParameter("isPay");//是否支付
        String isDeliver_str = req.getParameter("isDeliver");//是否收获
        String username = req.getParameter("username");//店铺名
        String uid_str = req.getParameter("uid");//用户id
        Integer isPay = -1;
        Integer isDeliver = -1;
        Integer uid = -1;
        //处理参数数据
        if (isPay_str != null && !isPay_str.equals("")) {
            isPay = Integer.parseInt(isPay_str);
        }
        if (isDeliver_str != null && !isDeliver.equals("")) {
            isDeliver = Integer.parseInt(isDeliver_str);
        }
        if (uid_str != null && !uid_str.equals("")) {
            uid = Integer.parseInt(uid_str);
        } else {
            error.setErrorInfo("网络开小差啦。。。");
            error.setErrorType(6);
        }
        if (username == null || username.equals("")) {
            username = null;
        }
        if (user == null) {
            error.setErrorInfo("请先登录。。。");
            error.setErrorType(1);
        } else {
            //验证用户身份
            System.err.println(user.getUid());
            if (user.getuType() == 0) {
                //只查询属于用户的订单
                System.err.println(isPay + isDeliver + uid + username);
                List<Order> orders = orderService.findAllByUid(isPay, isDeliver, uid, username);
                PageInfo<Order> pages = new PageInfo<Order>(orders);
                //验证ok 查询返回集合
                return JsonUtils.writeValueAsString(pages);
            } else {
                error.setErrorInfo("网络开小差了。。。");
                error.setErrorType(6);
            }

        }
        //权限认证失败  返回错误信息
        return JsonUtils.writeValueAsString(error);
    }

    //发货
    @RequestMapping("/upDeliver.do")
    @ResponseBody
    public String upStatus(String orderId, Integer isDeliver) {
        Error er = new Error();
        int result = 0;
        if (isDeliver == 0 || isDeliver == null) {
            isDeliver = 1;
        }
        result = orderService.upDeliver(orderId, isDeliver);
        if (result == 0) {
            er.setErrorType(5);
            er.setErrorInfo("发货失败。。");
        } else if (result == 1) {
            er.setErrorType(0);
            er.setErrorInfo("发货成功。。");
        }
        return JsonUtils.writeValueAsString(er);
    }

    /*
         退款模块
      */
    //同意退款
    @RequestMapping("/agree.do")
    @ResponseBody
    public String Agree(String orderId) {
        Error er = new Error();
        int result = 0;
        result = orderService.upRefund(orderId, 2);
        if (result == 0) {
            er.setErrorType(5);
            er.setErrorInfo("退款失败。。");
        } else if (result == 1) {
            er.setErrorType(0);
            er.setErrorInfo("退款成功。。");
        }
        return JsonUtils.writeValueAsString(er);
    }

    //拒绝退款
    @RequestMapping("/refuse.do")
    @ResponseBody
    public String Refuse(String orderId) {
        Error er = new Error();
        int result = 0;
        result = orderService.upRefund(orderId, 3);
        if (result == 0) {
            er.setErrorType(5);
            er.setErrorInfo("网络开小差了。。");
        } else if (result == 1) {
            er.setErrorType(0);
            er.setErrorInfo("已拒绝买家申请。。");
        }
        return JsonUtils.writeValueAsString(er);
    }

    //付款
    @RequestMapping("/Pay.do")
    @ResponseBody
    public String upPay(String orderId) {
        Error er = new Error();
        int result = 0;
        result = orderService.Pay(orderId);
        if (result == 0) {
            er.setErrorType(5);
            er.setErrorInfo("付款失败。。");
        } else if (result == 1) {
            er.setErrorType(0);
            er.setErrorInfo("支付成功。。");
        }
        return JsonUtils.writeValueAsString(er);
    }

    //付款  从购物车里付款
    @RequestMapping("shoppingPay.do")
    @ResponseBody
    public String shoppingPay(Integer uid, Integer bid, HttpServletRequest request) {
        Error e = new Error();
        User user = (User) request.getSession().getAttribute("loginUser");
        if(user == null){
            e.setErrorInfo("请先登录！");
            e.setErrorType(1);
            return JsonUtils.writeValueAsString(e);
        }
        if (uid == null || uid == 0) {
            uid = user.getUid();
        }
        Order o = new Order();
        //获取收货地址信息  默认第一个收货地址
        List<Address> address = addressService.findAllByUid(uid);
        if (address == null) { //地址为空让用户去添加地址
            e.setErrorType(2);
            e.setErrorInfo("请先添加收获地址在购买吧~");
            return JsonUtils.writeValueAsString(e);
        }
        //获得购物车里的订单信息
        ShoppingCart sc = shoppingCartService.findAllByUidAndBid(uid, bid);
        //计算总价  书记单价*书籍数量
        o.setTotalPrice(sc.getBid().getPrice() * sc.getCount());
        //生成订单号
        o.setOrderId(Long.toString(new Date().getTime()) + uid.toString() + bid.toString());
        System.out.println(o.getOrderId());
        //设置 商家id
        User u = new User();
        u.setUid(sc.getBid().getUid());
        o.setUid(u);
        //设置 买家id
        o.setBuyers(sc.getUid());
        o.setIsPay(1);
        //设置发货
        o.setIsDeliver(0);
        //设置收获状态
        o.setIsReceipt(0);
        //售后
        o.setIsRefund(0);
        //收货地址
        o.setAddressId(address.get(0));
        //执行订单添加操作
        int result1 = 0;
        int result2 = 0;
        result1 = orderService.PayToShopping(o);
        //删除购物车里的
        result2 = shoppingCartService.delShopping(uid, bid);
        if (result1 == result2 && result2 == 1) {
            e.setErrorType(0);
            e.setErrorInfo("购买成功！");
        } else {
            e.setErrorType(2);
            e.setErrorInfo("购买失败！");
        }
        return JsonUtils.writeValueAsString(e);
    }

    //从直接购买
    @RequestMapping("directlyPay.do")
    @ResponseBody
    public String directlyPay(Integer bid,HttpServletRequest req){
        //获得登录的用户信息
        User user = (User) req.getSession().getAttribute("loginUser");
        Error e = new Error();
        Order o = new Order();
        if(user == null){
            e.setErrorInfo("请先登录。。");
            e.setErrorType(1);
            return JsonUtils.writeValueAsString(e);
        }
        //获取数量
        String count_str = req.getParameter("count");
        //默认一个
        Integer count = 1;
        int result = 0;
        if (count_str != null && !count_str.equals("")) {
            //设置数量
            count = Integer.parseInt(count_str);
        }
        //获取收货地址信息  默认第一个收货地址
        List<Address> address = addressService.findAllByUid(user.getUid());
        if (address == null) { //地址为空让用户去添加地址
            e.setErrorType(2);
            e.setErrorInfo("请先添加收获地址在购买吧~");
            return JsonUtils.writeValueAsString(e);
        }
        //获得书籍信息
        Book bk = bookService.findByBid(bid);
        //计算总价  书记单价*书籍数量
        o.setTotalPrice(bk.getPrice() * count);
        //生成订单号
        o.setOrderId(Long.toString(new Date().getTime()) + user.getUid().toString() + bid.toString());
        System.out.println(o.getOrderId());
        //设置 商家id
        User u = new User();
        u.setUid(bk.getUid());
        o.setUid(u);
        //设置 买家id
        o.setBuyers(user);
        //是否支付
        o.setIsPay(1);
        //设置发货
        o.setIsDeliver(0);
        //设置收获状态
        o.setIsReceipt(0);
        //售后
        o.setIsRefund(0);
        //收货地址
        o.setAddressId(address.get(0));
        //执行订单添加操作
        int result1 = 0;
        int result2 = 0;
        result1 = orderService.PayToShopping(o);
        if (result1 == 1) {
            e.setErrorType(0);
            e.setErrorInfo("购买成功！");
        } else {
            e.setErrorType(2);
            e.setErrorInfo("购买失败！");
        }
        return JsonUtils.writeValueAsString(e);
    }


    //收货模块
    @RequestMapping("/receipt.do")
    @ResponseBody
    public String doReceipt(String orderId) {
        Error er = new Error();
        int result = 0;
        result = orderService.receipt(orderId);
        if (result == 0) {
            er.setErrorType(5);
            er.setErrorInfo("收货失败。。");
        } else if (result == 1) {
            er.setErrorType(0);
            er.setErrorInfo("收货成功。。");
        }
        return JsonUtils.writeValueAsString(er);
    }

    //退款
    @RequestMapping("/refund.do")
    @ResponseBody
    public String doRefund(String orderId) {
        Error er = new Error();
        int result = 0;
        result = orderService.refund(orderId);
        if (result == 0) {
            er.setErrorType(6);
            er.setErrorInfo("网络开小差了。。");
        } else if (result == 1) {
            er.setErrorType(0);
            er.setErrorInfo("商家审核中");
        }
        return JsonUtils.writeValueAsString(er);
    }

    //根据订单号获取订单信息
    @RequestMapping("/getOrderOne.do")
    @ResponseBody
    public String getOrderOne(String orderId) {
        Order order = orderService.findOneByOrderId(orderId);
        return JsonUtils.writeValueAsString(order);
    }

    //修改订单信息
    @RequestMapping("/upOrder.do")
    @ResponseBody
    public String upOrder(Order order) {
        Error er = new Error();
        int result = 0;
        result = orderService.upOrder(order);
        if (result == 0) {
            er.setErrorType(6);
            er.setErrorInfo("网络开小差了。。");
        } else if (result == 1) {
            er.setErrorType(0);
            er.setErrorInfo("修改成功！");
        }
        return JsonUtils.writeValueAsString(er);
    }

    //删除订单信息
    @RequestMapping("/delOrder")
    @ResponseBody
    public String delOrder(String orderId,HttpSession session) {
        Error er = new Error();
        int result = 0;
        User loginUser = (User)session.getAttribute("loginUser");
        result = orderService.delOrder(orderId, loginUser.getUid());
        if (result == 0) {
            er.setErrorType(6);
            er.setErrorInfo("网络开小差了。。");
        } else if (result == 1) {
            er.setErrorType(0);
            er.setErrorInfo("删除成功！");
        }
        return JsonUtils.writeValueAsString(er);
    }
}
